<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="一级标题" prop="firstLevelTitle">
        <el-select v-model="queryParams.firstLevelTitle" placeholder="请选择一级标题" clearable @change="handleQuery">
          <el-option v-for="item in thirdLevelTitles" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务状态" prop="deleted">
        <el-select v-model="queryParams.deleted" placeholder="请选择服务状态" clearable>
          <el-option v-for="dict in dict.type.service" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="showList" row-key="globalId" ref="treeTable"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <!-- 绑定标题ID列 -->
      <el-table-column label="绑定标题id" align="center">
        <template slot-scope="scope">
          {{ scope.row.id || '-' }}
        </template>
      </el-table-column>

      <!-- 展示图片列 -->
      <el-table-column label="展示图片" align="center">
        <template slot-scope="scope">
          <div class="image-container">
            <img v-if="scope.row.showPictures" :src="scope.row.showPictures" alt="服务图片" class="table-img" />
            <span v-else class="no-image-placeholder">无图片</span>
          </div>
        </template>
      </el-table-column>

      <!-- 展示标题列 -->
      <el-table-column label="展示的标题" align="center" prop="firstLevelTitle" />

      <!-- 服务介绍列 -->
      <el-table-column label="服务介绍" align="center">
        <template slot-scope="scope">
          <div class="ellipsis-text" :title="scope.row.showIntroduce">{{ scope.row.showIntroduce || '-' }}</div>
        </template>
      </el-table-column>

      <!-- 跳转路径列 -->
      <el-table-column label="跳转路径" align="center">
        <template slot-scope="scope">
          <div class="ellipsis-text" :title="scope.row.jumpPage">{{ scope.row.jumpPage || '-' }}</div>
        </template>
      </el-table-column>

      <el-table-column label="服务状态" align="center">
        <template slot-scope="scope">
          <div class="status-text" :title="(scope.row.deleted)">
            <span v-if="scope.row.deleted === 0">上架</span>
            <span v-else>下架</span>
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-if="canEdit(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
            v-if="canAdd(scope.row)">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-if="canDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改服务显示信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="绑定标题id" prop="secondaryTitleId">
          <el-input v-model="form.secondaryTitleId" placeholder="请输入绑定标题id" :disabled="true" />
        </el-form-item>
        <el-form-item label="展示图片的路径" prop="showPictures">
          <el-input v-model="form.showPictures" placeholder="请输入展示图片的路径" />
        </el-form-item>
        <el-form-item label="展示的标题" prop="showTitle">
          <el-input v-model="form.showTitle" placeholder="请输入展示的标题" />
        </el-form-item>
        <el-form-item label="服务介绍" prop="showIntroduce">
          <el-input v-model="form.showIntroduce" placeholder="请输入服务介绍" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="跳转路径" prop="jumpPage">
          <el-input v-model="form.jumpPage" placeholder="请输入跳转路径" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { servicemanageTree, getShow, delShow, addShow, updateShow } from "@/api/servicemanage/show";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// 获取一级标题
import { listAll } from "@/api/servicemanage/all"

export default {
  name: "Show",
  dicts: ['service'],
  components: {
    Treeselect,
  },
  data() {
    return {
      loading: true,
      showSearch: true,
      showList: [], // 原始数据（已树形结构）
      //获取服务状态的下拉框
      statusOptions: [],
      // 获取一级标题下拉框
      thirdLevelTitles: [],
      title: "",
      open: false,
      isExpandAll: true,
      queryParams: {
        title: null,
        deleted: null
      },
      form: {
        id: null,
        secondaryTitleId: null,
        showPictures: null,
        showTitle: null,
        showIntroduce: null,
        jumpPage: null,
        parentId: null,
      },
      // 添加表单验证规则
      rules: {
        secondaryTitleId: [
          { required: true, message: '请输入绑定标题ID', trigger: 'blur' }
        ],
        showTitle: [
          { required: true, message: '请输入展示标题', trigger: 'blur' }
        ],
        showPictures: [
          { required: true, message: '请输入展示图片路径', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    console.log('组件初始化，准备获取数据');
    this.getList();
    //获取一级标题显示的下拉框
    this.fetchalls();
  },
  methods: {

    // 判断是否允许编辑（三级节点或特殊二级节点）
    canEdit(row) {
      if (!row) return false;
      const isThirdLevel = row.level === 3;
      const isSpecialSecondLevel = row.level === 2 && (row.children === null || row.children.length === 0);
      return isThirdLevel || isSpecialSecondLevel;
    },

    // 判断是否允许新增（根据业务规则）
    canAdd(row) {
      if (!row) return false; // 根节点（未选中任何行时）
      if (row.level === 3) return false; // 三级节点下不能新增

      // 一级节点中仅"当季热门"（假设 id=1）允许新增二级节点
      if (row.level === 1 && row.id !== 1) return false;

      // 二级节点中，若 children 存在且非空，则允许新增子节点（否则不允许）
      if (row.level === 2 && row.children && row.children.length > 0) return true;

      return row.level === 0; // 根节点（初始化时允许新增一级节点）
    },
    // 判断是否允许删除（二级菜单或特殊三级菜单）
    canDelete(row) {
      if (!row) return false; // 未选中节点时不允许删除

      // 特殊三级菜单：允许删除的三级节点（如无子节点的三级菜单）
      const isThirdLevelAllowDelete = row.level === 3 &&
        (row.children === null || row.children.length === 0); // 无子节点的三级菜单

      // 二级菜单：允许删除的二级节点（根据业务规则，如非父节点或允许删除的父节点）
      const isSecondLevelAllowDelete = row.level === 2 &&
        // 示例：允许删除所有二级节点，或限制某些条件（如非"当季热门"的子节点）
        true; // 可根据实际业务调整判断逻辑

      return isThirdLevelAllowDelete || isSecondLevelAllowDelete;
    },
    /** 查询服务显示信息列表 */
    getList() {
      this.loading = true;
      this.showList = []; // 清空旧数据
      console.log('查询参数:', this.queryParams);
      servicemanageTree(this.queryParams).then((response) => {
        console.log('获取到原始数据，长度:', response.data?.length || 0);
        console.log('原始数据内容:', response.data);

        const processedData = this.processTreeData(response.data || []);
        console.log('处理后的树形数据，长度:', processedData.length);

        // 检查是否存在重复的 globalId
        const globalIds = new Set();
        const checkDuplicates = (nodes) => {
          nodes.forEach(node => {
            if (globalIds.has(node.globalId)) {
              console.error('发现重复的 globalId:', node.globalId, '节点:', node);
            }
            globalIds.add(node.globalId);
            if (node.children) {
              checkDuplicates(node.children);
            }
          });
        };
        checkDuplicates(processedData);

        this.showList = processedData;
        this.loading = false;

        // 数据加载完成后，根据当前状态设置展开/折叠
        this.$nextTick(() => {
          this.setInitialExpandedState();
        });
      }).catch(error => {
        this.loading = false;
        this.$modal.msgError('获取数据失败: ' + error.message);
      });
    },
    // 获取一级标题
    fetchalls() {
      listAll().then((response) => {
        // 校验响应数据
        if (!response || !Array.isArray(response.rows)) {
          console.error('接口返回数据格式异常');
          this.thirdLevelTitles = [];
          return;
        }

        // 筛选 upOneLevelId=0 的数据
        const filteredRows = response.rows.filter(item =>
          item.upOneLevelId === 0 &&
          item.firstLevelTitle // 可选：确保标题不为空
        );

        // 转换为下拉框所需格式
        this.thirdLevelTitles = filteredRows.map(item => ({
          value: item.firstLevelTitle, // 使用 id 作为 value（而非 upOneLevelId）
          label: item.firstLevelTitle || '无标题'
        }));
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.thirdLevelTitles = [];
      });
    },
    // 处理树形数据，添加全局唯一ID
    processTreeData(treeData, parentPath = '') {
      // 跟踪所有生成的 globalId
      const globalIdSet = new Set();

      // 检查同层级节点 id 是否重复
      const idSet = new Set();
      const hasDuplicate = treeData.some(node => {
        if (idSet.has(node.id)) {
          console.warn(`同层级节点 id 重复: ${node.id}`);
          return true;
        }
        idSet.add(node.id);
        return false;
      });
      if (hasDuplicate) {
        this.$modal.msgError('数据中存在同层级 id 重复，请检查！');
        return []; // 或处理重复数据
      }

      return treeData.map((node, index) => {
        // 生成全局唯一ID，格式: 父路径_当前节点ID
        const globalId = parentPath ? `${parentPath}_${node.id}` : `${node.id}`;

        // 检查是否有重复
        if (globalIdSet.has(globalId)) {
          console.error('发现重复的 globalId:', globalId, '节点:', node);
          // 添加时间戳确保唯一性
          const uniqueGlobalId = `${globalId}_${Date.now()}`;
          globalIdSet.add(uniqueGlobalId);
          const newNode = { ...node, globalId: uniqueGlobalId };

          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            newNode.children = this.processTreeData(node.children, uniqueGlobalId);
          }

          return newNode;
        }

        globalIdSet.add(globalId);
        const newNode = { ...node, globalId };

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          newNode.children = this.processTreeData(node.children, globalId);
        }

        return newNode;
      });
    },

    /** 查询服务显示信息下拉树结构 */
    getTreeselect() {
      servicemanageTree().then((response) => {
        this.showOptions = [];
        const rootNode = { id: 0, title: "顶级节点", children: response.data };
        this.showOptions.push(rootNode);
      }).catch(error => {
        this.$modal.msgError('获取树形结构失败: ' + error.message);
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        id: null,
        secondaryTitleId: null,
        showPictures: null,
        showTitle: null,
        showIntroduce: null,
        jumpPage: null,
        parentId: null
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },

    handleQuery() {
      this.getList();
    },

    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.handleQuery();
    },

    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row) {
        // 传递父节点的ID
        this.form.secondaryTitleId = row.id;
        // 若父节点是第三级，则禁止新增
        if (row.level === 3) {
          this.$modal.msgError('第三级节点下不能新增子节点');
          return;
        }

        // 另一种判断方式：通过节点标题
        // 2. 如果 children 固定为 null，说明不允许新增子节点
        if (row.level === 2 && row.children === null) {
          this.$modal.msgError('该节点不允许新增子节点');
          return;
        }

        // 只有"当季热门"（id=1）可以新增二级子节点
        if (row.level === 1 && row.id !== 1) {
          this.$modal.msgError('除"当季热门"外，其他一级节点不能新增子节点');
          return;
        }
        this.form.secondaryTitleId = row.id;
      } else {
        this.form.secondaryTitleId = 0; // 根节点（第一级）
      }
      this.open = true;
      this.title = "添加服务显示信息";
    },

    handleUpdate(row) {
      this.reset();
      // 判断是否为三级节点，或二级节点且无子节点（特殊二级菜单）
      const isThirdLevel = row.level === 3;
      const isSpecialSecondLevel = row.level === 2 && (row.children === null || row.children.length === 0);

      if (!row.id || !isThirdLevel && !isSpecialSecondLevel) {
        this.$modal.msgError('仅支持修改第三级菜单或特殊二级菜单');
        return;
      }

      console.log('准备更新数据,ID:', row.id);
      getShow(row.id).then((response) => {
        console.log('获取到要更新的数据:', response.data);
        this.form = { ...response.data };
        this.open = true;
        this.title = "修改服务显示信息";
      }).catch(error => {
        this.$modal.msgError('获取数据失败: ' + error.message);
      });
    },

    submitForm() {
      if (this.$refs.form) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log('提交表单数据:', this.form);
            const requestMethod = this.form.id ? updateShow : addShow;
            requestMethod(this.form).then(() => {
              this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError('操作失败: ' + error.message);
            });
          }
        });
      }
    },

    handleDelete(row) {
      if (!this.canDelete(row)) { // 使用相同的权限判断方法
        this.$modal.msgError('该节点不允许删除');
        return;
      }
      if (!row.id || row.deleted === undefined) {
        this.$modal.msgError('未选择有效数据');
        return;
      }

      this.$modal.confirm(`是否确认修改服务显示信息编号为"${row.id}"的数据项？`).then(() => {
        console.log('准备删除数据,ID:', row.id, '状态:', row.deleted);
        delShow(row.id, row.deleted).then(() => {
          this.getList();
          this.$modal.msgSuccess("修改成功");
        }).catch(error => {
          this.$modal.msgError('修改失败: ' + error.message);
        });
      });
    },

    /**
     * 设置初始展开状态
     */
    setInitialExpandedState() {
      if (!this.$refs.treeTable || !this.showList.length) return;

      this.showList.forEach(row => {
        this.$refs.treeTable.toggleRowExpansion(row, this.isExpandAll);

        if (row.children && row.children.length > 0) {
          this.toggleChildrenExpansion(row.children, this.isExpandAll);
        }
      });
    },

    /**
     * 切换全部节点展开/折叠状态
     */
    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll;

      this.$nextTick(() => {
        if (!this.$refs.treeTable) return;

        this.showList.forEach(row => {
          this.$refs.treeTable.toggleRowExpansion(row, this.isExpandAll);

          if (row.children && row.children.length > 0) {
            this.toggleChildrenExpansion(row.children, this.isExpandAll);
          }
        });
      });
    },

    /**
     * 递归处理子节点的展开/折叠状态
     */
    toggleChildrenExpansion(children, expanded) {
      children.forEach(row => {
        this.$refs.treeTable.toggleRowExpansion(row, expanded);

        if (row.children && row.children.length > 0) {
          this.toggleChildrenExpansion(row.children, expanded);
        }
      });
    }
  },
};
</script>

<style scoped>
.table-img {
  max-height: 60px;
  max-width: 100px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

.no-image-placeholder {
  display: inline-block;
  padding: 4px 8px;
  background-color: #f5f7fa;
  color: #909399;
  border-radius: 4px;
  font-size: 12px;
}

.ellipsis-text {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
